import os
import requests
import json
from PIL import Image
from io import BytesIO
from time import sleep

# 基本配置
TOTAL_USERS = 1000
API_BATCH = 500  # 每次最大请求500条
OUTPUT_DIR = "avatars_by_country"
USER_JSON = "users_1000.json"

proxies = {
    "http": "http://127.0.0.1:64300",
    "https": "http://127.0.0.1:64300",
}

def fetch_users(batch_size):
    url = f"https://randomuser.me/api/?results={batch_size}"
    response = requests.get(url,proxies=proxies, timeout=10)
    if response.status_code == 200:
        return response.json()["results"]
    else:
        raise Exception(f"Failed to fetch users: {response.status_code}")

def save_avatar(img_url, save_path):
    response = requests.get(img_url, timeout=10)
    if response.status_code == 200:
        img = Image.open(BytesIO(response.content))
        img = img.resize((256, 256))
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        img.save(save_path)
        return True
    return False

def format_gender(gender):
    return "male" if gender.lower() == "male" else "female"

def main():
    users = []
    total_fetched = 0
    while total_fetched < TOTAL_USERS:
        batch_size = min(API_BATCH, TOTAL_USERS - total_fetched)
        try:
            user_batch = fetch_users(batch_size)
            for user in user_batch:
                gender = format_gender(user["gender"])
                country = user["location"]["country"].replace(" ", "_").lower()
                name = f"{user['name']['first']} {user['name']['last']}"
                avatar_url = user["picture"]["large"]

                save_folder = os.path.join(OUTPUT_DIR, country, gender)
                avatar_filename = f"{gender}_{total_fetched + 1:04d}.jpg"
                save_path = os.path.join(save_folder, avatar_filename)

                success = save_avatar(avatar_url, save_path)
                if success:
                    users.append({
                        "username": name,
                        "gender": gender,
                        "country": country,
                        "avatar": save_path.replace("\\", "/")
                    })
                    total_fetched += 1

                if total_fetched >= TOTAL_USERS:
                    break
            sleep(1)  # 防止过快请求
        except Exception as e:
            print(f"[!] Error: {e}")
            sleep(3)

    # 保存用户信息到 JSON
    with open(USER_JSON, "w", encoding="utf-8") as f:
        json.dump(users, f, indent=2, ensure_ascii=False)

    print(f"[✔] 完成！共生成 {len(users)} 个用户，数据保存在 {USER_JSON}")

if __name__ == "__main__":
    main()
